package com.evan.uyclub;

import android.Manifest;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;

import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.downloader.Error;
import com.downloader.OnDownloadListener;
import com.downloader.PRDownloader;
import com.evan.uyclub.Other.AppMethods;
import com.evan.uyclub.Other.FileUtil;
import com.evan.uyclub.Other.SetClass;
import com.evan.uyclub.Other.VPNActivity;
import com.github.ybq.android.spinkit.SpinKitView;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.gyf.immersionbar.ImmersionBar;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.sdsmdg.tastytoast.TastyToast;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import me.everything.android.ui.overscroll.OverScrollDecoratorHelper;

/**
 * @noinspection AccessStaticViaInstance
 */
public class MainActivity extends AppCompatActivity {
    ObjectAnimator objectAnimator;
    ObjectAnimator objectAnimator1;
    ObjectAnimator objectAnimator2;
    ObjectAnimator objectAnimator3;
    private BottomSheetDialog dialog;
    private TextView app_name, Hold_one, Hold_two, Hold_three, up_home, about_app;
    private ImageView app_icon, app_earth;
    private SpinKitView spin_kit;
    private Object RotateAnimation;
    // 下载APK目录
    private String apkPath;
    // 下载进度
    private TextView mProgressText;
    private View activity;
    private BottomSheetDialog pop;
    private String new_url, aixin;
    private MaterialEditText users;
    private SharedPreferences.Editor editor;
    private String user;
    private String pass = "jfkjcyxf666";
    private TwinklingRefreshLayout huitan, login_smark;
    private SharedPreferences data;
    private LinearLayout icon_dad;

    /**
     * 期末考试要来了，要开始复习了，等考完试就完成这个软件并发布到应用商店，差不多也写完了~大家冲~ 2022
     * 期末考试要来了，要开始复习了，等考完试就完成这个软件并发布到应用商店，差不多也写完了~大家冲~ 2023 都一年了
     * 2024年了，哎真快，快实习了都。
     **/
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
        // requestWindowFeature(Window.FEATURE_NO_TITLE); //无title
        // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); //全屏设置
        //vpn检测
        VPNActivity vpnActivity = new VPNActivity(this);
        //设置状态栏
        ImmersionBar.with((Activity) this)
                .statusBarColor(R.color.main_back) // 状态栏颜色
                .navigationBarColor(R.color.main_back) // 导航栏深色
                .statusBarDarkFont(true) // 状态栏深色
                .navigationBarDarkIcon(true) // 导航栏深色
                .fitsSystemWindows(true) // 解决状态栏和布局重叠问题
                .init();
        //获取id进行回弹效果。
        huitan = findViewById(R.id.huitan);
        huitan.setPureScrollModeOn();
        //和逐渐显示动画
        objectAnimator = objectAnimator.ofFloat(huitan, "alpha", 0f, 1f);
        objectAnimator.setDuration(1500);
        objectAnimator.start();
        //让首页大动画连续运动
        /*GifImageView gifImageView=findViewById(R.id.image1);*/
        app_earth = findViewById(R.id.activity_earth);
        Earth_XZ();
        //OverScrollDecoratorHelper.setUpStaticOverScroll(app_earth,OverScrollDecoratorHelper.ORIENTATION_HORIZONTAL); //对earth设置水平方向的回弹
        objectAnimator1 = objectAnimator.ofFloat(app_earth, "translationX", 0f, 20f, 0f);
        objectAnimator2 = ObjectAnimator.ofFloat(app_earth, "translationX", 0f, -20f, 0f);
        objectAnimator3 = objectAnimator.ofFloat(app_earth, "translationX", 0f, 20f, 0f);
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.play(objectAnimator1).with(objectAnimator2).before(objectAnimator3).before(objectAnimator3);
        animatorSet.setDuration(8000);
        animatorSet.start();
        app_name = findViewById(R.id.app_name);
        objectAnimator = objectAnimator.ofFloat(app_name, "alpha", 0f, 1f); //动画设置，alpha为参数
        objectAnimator.setDuration(2000);//动画时间
        objectAnimator.start();//运行动画
        OverScrollDecoratorHelper.setUpStaticOverScroll(app_name, OverScrollDecoratorHelper.ORIENTATION_HORIZONTAL); //对文本设置水平方向的回弹
        /*OverScrollDecoratorHelper.setUpStaticOverScroll(app_name,OverScrollDecoratorHelper.ORIENTATION_VERTICAL);//垂直方向上可以回弹*/
        app_icon = findViewById(R.id.app_icon);
        objectAnimator = objectAnimator.ofFloat(app_icon, "alpha", 0f, 1f);
        objectAnimator.setDuration(2000);
        objectAnimator.start();
        /*icon_dad=findViewById(R.id.icon_dad); //线性布局动画不了*/
        OverScrollDecoratorHelper.setUpStaticOverScroll(app_icon, OverScrollDecoratorHelper.ORIENTATION_HORIZONTAL);//对icon可以水平弹窗
        /*OverScrollDecoratorHelper.setUpStaticOverScroll(app_icon,OverScrollDecoratorHelper.ORIENTATION_VERTICAL);//icon垂直方向上*/
        //对文本进行字体修改，字体库在main-assets里面。
        app_name.setTypeface(Typeface.createFromAsset(getAssets(), "space.ttf"));
        //这是加载中动画库调用
        /*ProgressBar spin_kit = (ProgressBar) findViewById(R.id.spin_kit);
        Sprite sp = new DoubleBounce();
        spin_kit.setIndeterminateDrawable(sp);*/
        //关于文本设置
        about_app = findViewById(R.id.about_app);
        objectAnimator = objectAnimator.ofFloat(about_app, "alpha", 0f, 1f); //动画设置，alpha为参数
        objectAnimator.setDuration(2000);//动画时间
        objectAnimator.start();//运行动画
        OverScrollDecoratorHelper.setUpStaticOverScroll(about_app, OverScrollDecoratorHelper.ORIENTATION_HORIZONTAL); //对文本设置水平方向的回弹
        about_app.setTypeface(Typeface.createFromAsset(getAssets(), "rubik.ttf"));
        if (isNetworkAvailable(MainActivity.this)) {
            //新版本
            News();
            // 检测新版本 再运行整个App IfFrist();
            // 这样提示的话不好看
            /*TastyToast.makeText(getApplicationContext(), "欢迎主人喽~", TastyToast.LENGTH_LONG, TastyToast.SUCCESS);*/
        } else {
            TastyToast.makeText(getApplicationContext(), "请检查网络！", TastyToast.LENGTH_LONG, TastyToast.ERROR);
            YoYo.with(Techniques.Tada)
                    .duration(1000)
                    .repeat(5)
                    .playOn(app_earth);
        }
    }

    //新版本
    private void News() {
        String Newban = AppMethods.getLocalVersionName(this);
        System.out.println(Newban);
        EasyHttp.get(SetClass.getUrl() + "uyapi/preview_newapp.php")
                .params("keeper", SetClass.getAdmin())
                .params("api", SetClass.getApi())
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onSuccess(String response) {
                        try {
                            JSONObject jsonData = new JSONObject(response);
                            String new_content = jsonData.getString("newappcontent");
                            String new_ban = jsonData.getString("newappedition");
                            aixin = jsonData.getString("newappimgurl");
                            new_url = jsonData.getString("newappdowurl");

                            if (!Newban.equals(new_ban)) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        pop = new BottomSheetDialog(MainActivity.this);
                                        activity = getLayoutInflater().inflate(R.layout.pop_update, null);
                                        pop.setContentView(activity);
                                        pop.setCancelable(false); // 返回键是否允许关闭
                                        pop.setCanceledOnTouchOutside(false); // 点击界面是否允许关闭
                                        pop.show();
                                        pop.getWindow().findViewById(R.id.design_bottom_sheet).setBackgroundResource(android.R.color.transparent);
                                        TextView title = activity.findViewById(R.id.title);
                                        title.setTypeface(Typeface.createFromAsset(getAssets(), "space.ttf"));
                                        title.setText(new_ban);
                                        TextView content = activity.findViewById(R.id.content);
                                        content.setTypeface(Typeface.createFromAsset(getAssets(), "rubik.ttf"));
                                        content.setText(new_content);
                                        LinearLayout update = activity.findViewById(R.id.update);
                                        mProgressText = activity.findViewById(R.id.progress);
                                        update.setOnClickListener(v -> { // 点击文件下载
                                            if (mProgressText.getText().toString().equals("马上更新")) {
                                                mProgressText.setText("正在下载");
                                                downloadMethods(); // 下载APK
                                            } else if (mProgressText.getText().toString().equals("安装")) {
                                                installApk(); // 安装APK
                                            } else if (mProgressText.getText().toString().equals("下载失败")) {
                                                TastyToast.makeText(MainActivity.this, "亲，可能在维护软件哦~", TastyToast.LENGTH_SHORT, TastyToast.ERROR).show();
                                            } else {
                                                Looper.prepare();
                                                TastyToast.makeText(MainActivity.this, "正在下载", TastyToast.LENGTH_SHORT, TastyToast.ERROR).show();
                                                Looper.loop();
                                            }
                                        });
                                    }
                                });
                            } else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        IfFrist();
                                    }
                                });
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    public void newToast(View view) {
        TastyToast.makeText(this, "亲，这次是强制更新哦~", TastyToast.LENGTH_SHORT, TastyToast.WARNING).show();
    }

    public void downloadMethods() { // 执行下载
        String path = "/UYClub/";
        String name = "UyClub.apk";
        Context context = MainActivity.this;
        if (!FileUtil.isExistFile(FileUtil.getExternalStorageDir().concat(path))) {
            FileUtil.makeDir(FileUtil.getExternalStorageDir().concat(path));
        }
        int downloadIdOne = PRDownloader.download(new_url, FileUtil.getExternalStorageDir().concat(path), name)
                .build()
                .setOnStartOrResumeListener(() -> {
                })
                .setOnPauseListener(() -> {
                })
                .setOnCancelListener(() -> {
                })
                .setOnProgressListener(progress -> {
                    long progressPercent = progress.currentBytes * 100 / progress.totalBytes;
                    mProgressText.setText(progressPercent + "％");
                })
                .start(new OnDownloadListener() {
                    @Override
                    public void onError(Error error) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                TastyToast.makeText(MainActivity.this, "下载失败，请重试", TastyToast.LENGTH_SHORT, TastyToast.ERROR).show();
                                mProgressText.setText("下载失败");
                            }
                        });
                    }

                    @Override
                    public void onDownloadComplete() {
                        android.media.MediaScannerConnection.scanFile((Activity) MainActivity.this, new String[]{FileUtil.getExternalStorageDir().concat(path) + name}, null, new android.media.MediaScannerConnection.OnScanCompletedListener() {
                            public void onScanCompleted(String str, Uri uri) {
                                Intent intent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
                                intent.setData(uri);
                                ((Activity) MainActivity.this).sendBroadcast(intent);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        TastyToast.makeText(MainActivity.this, "下载成功，请安装,记得删除下载的安装包哦", TastyToast.LENGTH_LONG, TastyToast.SUCCESS).show();
                                        apkPath = FileUtil.getExternalStorageDir().concat(path) + name;
                                        Log.e("TAG", apkPath);
                                        mProgressText.setText("安装");
                                    }
                                });
                            }
                        });
                    }
                });

    }

    /*
     * 下载到本地后执行安装
     */
    @SuppressLint("ObsoleteSdkInt")
    private void installApk() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File apkFile = new File(apkPath);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri uri = FileProvider.getUriForFile(this, this.getPackageName() + ".fileprovider", apkFile);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        startActivity(intent);
    }

    //判断有无网络
    public boolean isNetworkAvailable(Activity activity) {
        Context context = activity.getApplicationContext();
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager == null) {
            return false;
        } else {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo.length > 0) {
                for (int i = 0; i < networkInfo.length; i++) {
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    //Earth 动画
    private void Earth_XZ() {
        Animation Earth = AnimationUtils.loadAnimation(MainActivity.this, R.anim.earth_zd);
        app_earth.startAnimation(Earth);
    }

    // 第一次启动
    private void IfFrist() {
        //判断是否第一次进软件
        SharedPreferences sharedPreferences = this.getSharedPreferences("share", MODE_PRIVATE);
        //这里。让他获取，是不是第一次。默认是第一的。true
        boolean isFirstRun = sharedPreferences.getBoolean("isFirstRun", true);
        editor = sharedPreferences.edit();
        if (isFirstRun) {
            editor.putBoolean("isFirstRun", false);//我得做个标记。改成false。
            editor.commit();     //提交到本地，存起来
            //是第一次
            //获取权限
            BottomSheetDialog pop = new BottomSheetDialog(MainActivity.this);
            View activity = getLayoutInflater().inflate(R.layout.pop_quuanxian, null);
            pop.setContentView(activity);
            pop.setCancelable(false); // 返回键是否允许关闭
            pop.setCanceledOnTouchOutside(false); // 点击界面是否允许关闭
            pop.show();
            pop.getWindow().findViewById(R.id.design_bottom_sheet).setBackgroundResource(android.R.color.transparent);
            TextView title = activity.findViewById(R.id.title);
            title.setTypeface(Typeface.createFromAsset(getAssets(), "space.ttf"));
            TextView content = activity.findViewById(R.id.content);
            content.setTypeface(Typeface.createFromAsset(getAssets(), "rubik.ttf"));
            LinearLayout update = activity.findViewById(R.id.update);
            update.setOnClickListener(v -> {
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        1);
                pop.dismiss();
                Start();
            });
        } else {
            /*editor.putBoolean("isFirstRun", true);//我得做个标记。改成false。
            editor.commit();     //提交到本地，存起来*/
            //不是第一次
            Nooneopen();
        }
    }

    //声明弹窗
    public void ActivityRegd() {
        BottomSheetDialog dialog = new BottomSheetDialog(MainActivity.this);
        View dialog1 = getLayoutInflater().inflate(R.layout.dialog_loading, null);
        dialog.setContentView(dialog1);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.getWindow().findViewById(R.id.design_bottom_sheet).setBackgroundResource(R.color.bantouming);
        this.dialog = dialog;
    }

    //不是第一次
    private void Nooneopen() {
        //进行跳转
        Start();
    }


    //不是第一，自动登录成功后跳转到首页
    private void Start() {
        Handler mHandler = new Handler();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //逐渐变淡
                /*objectAnimator = objectAnimator.ofFloat(huitan, "alpha", 1f, 0f);
                objectAnimator.setDuration(500);
                objectAnimator.start();*/
                //进行跳转
                startActivity(new Intent(MainActivity.this, StartActivity.class));
                finish();
                //跳转同时运行动画，动画要放到anim下面
                /*overridePendingTransition(R.anim.start_in,R.anim.end_in);*/
                overridePendingTransition(R.anim.activity_visible, R.anim.activity_gone);
            }
        }, 2000); // 延时3秒
    }

    //输入框，文本，个个控件跳动动画
    public void activty_name_gif(View view) {
        YoYo.with(Techniques.Tada)
                .duration(500)
                .repeat(0)
                .playOn(app_name);//app名跳动字动画
    }

    public void activty_icon_gif(View view) {
        YoYo.with(Techniques.Tada)
                .duration(500)
                .repeat(0)
                .playOn(app_icon);//app icon跳动动画
    }

    public void activity_earth(View view) {
        YoYo.with(Techniques.Tada)
                .duration(1000)
                .repeat(0)
                .playOn(app_earth);//earht跳动动画
    }

    public void activity_about(View view) {
        YoYo.with(Techniques.Tada)
                .duration(1000)
                .repeat(0)
                .playOn(about_app);//about跳动动画
    }
}